package com.lk.security.authentication;

import com.lk.base.result.Result;
import com.lk.security.properties.LoginResponseType;
import com.lk.security.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: lk-security-parent
 * @description: 自定义认证失败处理响应器
 * @author: Aspirin
 * @create: 2020-05-26 20:25
 */
@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
  // public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

  private static final Logger logger =
      LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);
  @Autowired SecurityProperties securityProperties;

  /**
   * 认证失败处理器
   *
   * @param request request
   * @param response response
   * @param exception exception
   * @throws IOException IOException
   */
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
      throws IOException, ServletException {
    if (LoginResponseType.JSON.equals(securityProperties.getAuthentication().getLoginType())) {
      Result result = Result.build(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
      response.setContentType("application/json;charset=UTF-8");
      response.getWriter().write(result.toJsonString());
    } else {
      // 重定向 到登录页面要加上error
      // 获取上次请求路径加上error后缀
      String referer = request.getHeader("Referer");
      logger.info("referer:{}", referer);
      // 如果下面有值,则认为是多端登录,直接返回一个登录地址
      Object toAuthentication = request.getAttribute("toAuthentication");
      String lastUrl =
          toAuthentication != null
              ? securityProperties.getAuthentication().getLoginPage()
              : StringUtils.substringBefore(referer, "?");
      logger.info("上次请求的路径:{}", lastUrl);
      super.setDefaultFailureUrl(lastUrl + "?error");
      super.onAuthenticationFailure(request, response, exception);
    }
  }
}
